package com.iwinding.ladygg.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/23.
 */
public class GsonUtil {

    private Gson gson;

    private static GsonUtil util;

    private GsonUtil() {
        gson = new Gson();
    }

    public static GsonUtil getInstance() {
        if (util == null) {
            util = new GsonUtil();
        }
        return util;
    }


    public <T> List<T> jsonToArray(String result, Class<T> zz) {
        Type type = new TypeToken<List<JsonObject>>()
        {}.getType();
        List<JsonObject> jsonObjects = new Gson().fromJson(result, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects)
        {
            arrayList.add(new Gson().fromJson(jsonObject, zz));
        }
        return arrayList;
    }

    public <T> T formJson(String jsonStr, Class<T> zz) {
        return gson.fromJson(jsonStr, zz);
    }

    public String toJson(Object object) {
        return gson.toJson(object);
    }

    public <T> String jsonToList(List<T> lists) {
        Type type = new TypeToken<List<T>>() {}.getType();
        return gson.toJson(lists, type);
    }

}
